<template>
	<view class="page">
		<!-- 轮播图 -->
		<swiper 
		class="banner-box" 
		:indicator-dots="goodsObj.gallery && goodsObj.gallery.length > 1 ? true : false" 
		indicator-active-color="#E81526"
		:autoplay="true" 
		:interval="3000" 
		:duration="1000">
			<swiper-item class="banner-item" v-for="(item,index) in goodsObj.gallery" :key="index">
				<image class="banner-img" :src="item"></image>
			</swiper-item>
		</swiper>
		<view class="info-box" v-if="goodsObj.info">
			<view class="u-flex u-flex-items-center">
				<view class="goods-price">
					￥{{shop_price}}
				</view>
				<view class="goods-market_price">
					{{goodsObj.info.market_price}}
				</view>
			</view>
			<view class="goods-name u-line-2">
				{{goodsObj.info.goods_name}}
			</view>
		</view>
		<!-- 优惠 -->
		<view class="discount">
			{{discount}}
		</view>
		<!-- 规格数量 -->
		<u-cell-group :border="false">
			<u-cell :border="false" :title="'已选择 ' + currentSkuValListStr" :isLink="true"
			rightIconStyle="fontSize: 40rpx;" titleStyle="paddingTop: 20rpx;paddingBottom: 20rpx;" @click="onOpenSelect"></u-cell>
			<u-cell :border="false" title="用户评价" :isLink="true"
			rightIconStyle="fontSize: 40rpx;" titleStyle="paddingTop: 20rpx;paddingBottom: 20rpx;" @click="onEvaluate"></u-cell>
			<!-- <u-cell :border="false" title="浏览量" :value="goodsObj.hitCounts"></u-cell> -->
		</u-cell-group>
		<u-gap height="20rpx"></u-gap>
		<!-- 商品详情 -->
		<u-parse v-if="goodsObj.info" :content="goodsObj.info.goods_desc"></u-parse>
		<view class="question-line">
			<u-divider text="常见问题" textSize="28rpx" textColor="#333333" lineColor="#999999"></u-divider>
		</view>
		<view class="question-list">
			<view class="question-item" v-for="(item,index) in goodsObj.issue" :key="index">
				<view class="question-item_title">
					{{item.question}}
				</view>
				<view class="question-item_desc">
					{{item.answer}}
				</view>
			</view>
		</view>
		<!-- 大家都在看 -->
		<view class="question-line">
			<u-divider text="大家都在看" textSize="28rpx" textColor="#333333" lineColor="#999999"></u-divider>
		</view>
		<view class="other-list">
			<view class="item-box" 
			@tap="goDetail(item.id,item.name)"
			v-for="(item,index) in goodsObj.productLookList" 
			:key="item.id">
				<image class="cover" :src="item.list_pic_url" mode=""></image>
				<view class="name u-line-1">{{item.name}}</view>
				<view class="price">￥{{item.retail_price}}</view>
			</view>
		</view>
		<!-- 底部 -->
		<view class="bottom-btns">
			<!-- 收藏 -->
			<view class="item-box min-box" @tap="onCollect">
				<uni-icons type="star" size="56rpx" :color="isCollect ? '#b4282d' : '#888888'"></uni-icons>
			</view>
			<!-- 客服 -->
			<view class="item-box min-box" @tap="onCall">
				<u-icon name="kefu-ermai" size="50rpx" color="#888888"></u-icon>
			</view>
			<!-- 购物车 -->
			<view class="item-box min-box" style="position: relative;" @tap="goCart">
				 <u-badge type="error" :max="99" :value="allNumber" :offset="[10,10]" :absolute="true"></u-badge>
				<uni-icons type="cart" size="60rpx" color="#888888"></uni-icons>
			</view>
			<!-- 加入购物车 -->
			<view class="item-box max-box">
				<text class="cart-text" @tap="addCard">加入购物车</text>
			</view>
			<!-- 立即购买 -->
			<view class="item-box max-box" @tap="onOpenSelect">
				<text class="join-text">立即购买</text>
			</view>
			<!-- 规格弹窗 -->
			<uni-popup ref="selectPopup" type="bottom" :safeArea="false">
				<view class="select-box">
					<view class="select-title">
						<uni-icons type="closeempty" size="40rpx" color="#999999" @tap="onClose"></uni-icons>
					</view>
					<!-- 商品 -->
					<view class="goods-info" >
						<image v-if="goodsObj.info" class="cover" :src="goodsObj.info.goods_thumb"></image>
						<view class="info-desc">
							<view class="info-desc_price">价格: ￥{{currentSelectGoods.price ? currentSelectGoods.price : shop_price}}</view>
							<view v-if="goodsObj.info" class="info-desc_number">库存: {{currentSelectGoods.stock ? currentSelectGoods.stock : goods_number}}</view>
							<view class="info-desc_number">请选择数量</view>
						</view>
					</view>
					<scroll-view class="select-list">
						<view class="select-item" v-for="(item,index) in goodsObj.goodsSkuNameList" :key="item.skuNameId" >
							<view class="select-item_title">{{item.skuName}}</view>
							<view class="select-item-list">
								<view 
								@tap="onSelect(index,sItem,sIndex)"
								class="select-item-name" 
								:class="item.itemIndex === sIndex ? 'select-active' : ''"
								v-for="(sItem,sIndex) in item.skuValList"
								:key="sItem.skuValId">{{sItem.skuVal}}</view>
							</view>
						</view>
						<view class="select-item">
							<view class="select-item_title">数量</view>
							<uni-number-box 
							v-if="goodsObj.info"
							v-model="currentNumber" 
							background="#f5f5f5" 
							:min="1" 
							:max="parseInt(currentSelectGoods.stock ? currentSelectGoods.stock : goods_number)"></uni-number-box>
						</view>
					</scroll-view>
					<view class="popup-bottom">
						<view class="popup-bottom_item join-btn" @tap="addCard">加入购物车</view>
						<view class="popup-bottom_item play-btn" @tap="onSubmit">立即购买</view>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import {getGoodsDetailApi,getGoodsDiscountApi, addGoodsCartApi,collectApi, updateGoodsApi} from '@/api/goods.js'
	import {mapState} from 'vuex'
	export default {
		computed: {
			...mapState(['user_id','token', 'hasLogin']),
			currentSkuValListStr: function() {
				let str = ''
				for (let i = 0; i < this.currentSkuValList.length; i++) {
					if(i === this.currentSkuValList.length - 1) {
						str += this.currentSkuValList[i].skuVal
					}else {
						str += this.currentSkuValList[i].skuVal + '-'
					}
				}
				return str
			}
		},
		data() {
			return {
				goods_id: null,
				goodsObj: {},
				discount: '', // 优惠
				allNumber: 0,
				currentNumber: 1,
				currentSelectGoods: {},
				currentSkuValList: [],
				isCollect: false, // 是否收藏
				shop_price: 0, // 商品价格
				goods_number: 0,
			};
		},
		onLoad({goods_id}) {
			this.goods_id = goods_id
			this.getGoodsDetail()
			this.getGoodsDiscount()
		},
		onShareAppMessage() {
			return {
				title: this.goodsObj.info.goods_name
			}
		},
		onShareTimeline() {
			return {
				title: this.goodsObj.info.goods_name
			}
		},
		methods: {
			// 购买
			async onSubmit() {
				// 判断是否登录
				if(!this.hasLogin) {
					uni.showToast({
						title: '请先登录!',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					},300)
					return
				}
				let sku = ''
				for (let i = 0; i < this.currentSkuValList.length; i++) {
					if(i === this.currentSkuValList.length -1) {
						sku += this.currentSkuValList[i].skuValId
					}else {
						sku += this.currentSkuValList[i].skuValId + ','
					}
				}
				// 更新到立即购买
				const res = await updateGoodsApi({
					goods_id: this.goods_id,
					sku: sku ? sku : 'n,u,l,l',
					num: this.currentNumber,
					user_id: this.user_id,
					token: this.token,
					product_id: this.goodsObj.info.productId
				})
				uni.navigateTo({
					url: `/pages/aPackage/orderConfirm/orderConfirm?goods_id=${this.goods_id}&number=${this.currentNumber}`
				})
			},
			// 跳转购物车
			goCart() {
				this.$store.commit('SET_TABBAR_INDEX',3)
				uni.switchTab({
					url: '/pages/cart/cart'
				})
			},
			// 加入购物车
			async addCard() {
				// 判断是否登录
				if(!this.hasLogin) {
					uni.showToast({
						title: '请先登录!',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					},300)
					return
				}
				let sku = ''
				for (let i = 0; i < this.currentSkuValList.length; i++) {
					if(i === this.currentSkuValList.length -1) {
						sku += this.currentSkuValList[i].skuValId
					}else {
						sku += this.currentSkuValList[i].skuValId + ','
					}
				}
				const res = await addGoodsCartApi({
					goods_id: this.goods_id,
					sku: sku ? sku : 'n,u,l,l',
					user_id: this.user_id,
					num: this.currentNumber,
					token: this.token,
					product_id: this.goodsObj.info.productId
				})
				this.$refs.selectPopup.close()
				this.allNumber = this.allNumber + this.currentNumber
				this.currentNumber = 1
				uni.showToast({
					title: '加入成功!'
				})
			},
			// 选择
			onSelect(currentIndex,currentItem,sIndex) {
				// 根据 skuValId 查找
				const goodsSkuList = this.goodsObj.goodsSkuList
				this.goodsObj.goodsSkuNameList[currentIndex].itemIndex = sIndex
				this.getGoodsArr()
			},
			onClose() {
				this.$refs.selectPopup.close()
			},
			// 规格选择
			onOpenSelect() {
				this.$refs.selectPopup.open()
			},
			// 评价
			onEvaluate() {
				
			},
			// 收藏
			async onCollect() {
				const res = await collectApi({
					user_id: this.user_id,
					token: this.token,
					collect_status: this.isCollect,
					goods_id: this.goods_id
				})
				uni.showToast({
					title: this.isCollect ? '取消收藏成功' : '收藏成功'
				})
				this.isCollect = !this.isCollect
			},
			// 拨打电话
			onCall() {
				uni.showModal({
					title: '提示',
					content: `确定拨打电话: ${this.goodsObj.kefu_tel.val}吗?`,
					success: (e) => {
						if(e.confirm) {
							uni.makePhoneCall({
								phoneNumber: this.goodsObj.kefu_tel.val
							})
						}
					}
				})
			},
			goDetail(goods_id,goods_name) {
				uni.navigateTo({
					url: `/pages/aPackage/goodsDetail/goodsDetail?goods_id=${goods_id}&goods_name=${goods_name}`
				})
			},
			// 获取商品优惠
			async getGoodsDiscount() {
				const res = await getGoodsDiscountApi({
					goods_id: this.goods_id
				})
				this.discount = res.data.discount
			},
			// 获取商品详情
			async getGoodsDetail() {
				let params = {
					goods_id: this.goods_id,
					// #ifdef MP-WEIXIN
					platform: 'MP-WEIXIN',
					// #endif
					// #ifdef H5
					platform: 'H5',
					// #endif
					// #ifdef APP-PLUS
					platform: 'APP-PLUS',
					// #endif
				}
				if(this.hasLogin) {
					params.user_id = this.user_id
				}
				const res = await getGoodsDetailApi(params)
				try{
					this.setHistoryList({
						goods_id: res.data.info.goods_id,
						goods_thumb: res.data.info.goods_thumb
					})
					uni.setNavigationBarTitle({
						title: res.data.info.goods_name
					})
					// 当前商品加入购物车数量
					this.allNumber = parseInt(res.data.allnumber)
					
					// 新增是否选择属性
					let goodsSkuNameList =  res.data.goodsSkuNameList
					for (let i = 0; i < goodsSkuNameList.length; i++) {
						// 默认选中第一个
						goodsSkuNameList[i].itemIndex = 0
						this.currentSkuValList.push(goodsSkuNameList[i].skuValList[0])
					}
					res.data.goodsSkuNameList = goodsSkuNameList
					this.goodsObj = res.data
					// 获取当前默认选择的商品
					this.currentSelectGoods = res.data.defaultSkuData
					const {collect = false, shop_price = 0, goods_number = 0} = res.data.info
					this.isCollect = collect
					this.shop_price = shop_price
					this.goods_number = goods_number
				}catch(e){
					//TODO handle the exception
					console.log('error')
				}
				
			},
			// 加入历史
			setHistoryList(data) {
				// 获取当前历史记录
				let historyList = uni.getStorageSync('historyList') || []
				// 最多展示100条
				if(historyList.length >= 100) {
					historyList.splice(99,1)
				}
				// 判断是否存在当前商品
				for (let i = 0; i < historyList.length; i++) {
					if(historyList[i].goods_id === data.goods_id) {
						historyList.splice(i,1)
					}
				}
				historyList.unshift(data)
				uni.setStorageSync('historyList',historyList)
			},
			// 根据当前skuValId 禁用无数量的属性
			getGoodsArr(skuNameIndex, skuValId,data) {
				// 计算当前数组
				// this.goodsObj.goodsSkuList.forEach((item,index) => {
					
				// })
				let arr = []
				this.goodsObj.goodsSkuNameList.forEach((item,index) => {
					arr.push(item.skuValList[item.itemIndex])
				})
				this.currentSkuValList = arr
			}
		}
	}
</script>

<style lang="scss" scoped>
@import "@/pages/aPackage/goodsDetail/goodsDetail.scss"
</style>
